<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogReAdd.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogReAdd.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    @close="closeDialog(false)"
  >
    <el-row v-loading="loading" :gutter="20">
      <el-col :span="6" :offset="0">
        <el-timeline v-if="auditLog && auditLog.length > 0">
          <el-timeline-item v-for="item in auditLog" :key="item.id" :timestamp="item.createTime" placement="top">
            <el-card style="padding: 5px">
              <div style="font-weight: bold; font-size: 14px">
                {{ item.flowEngineName }}
                &nbsp;
                <el-tag v-if="item.auditStatus !== -1" :type="item.auditStatus === 1 ? '' : 'info'">{{
                  item.auditStatusName
                }}</el-tag>
                &nbsp;
                <el-tag v-if="item.auditIdea !== 0" :type="item.auditIdea === 1 ? 'success' : 'danger'">{{
                  item.auditIdeaName
                }}</el-tag>
              </div>
              <p style="text-indent: 1em; line-height: 10px">{{ item.auditIdeaContent }}</p>
              <p style="text-indent: 1em; line-height: 10px">{{ item.auditTime }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂未审核记录" />
      </el-col>
      <el-col :span="18" :offset="0">
        <el-descriptions border title="" :column="2">
          <el-descriptions-item label="项目名称">{{ detailInfo.projectName }}</el-descriptions-item>
          <el-descriptions-item label="项目编号">{{ detailInfo.projectCode }}</el-descriptions-item>
          <el-descriptions-item label="项目负责人">{{ detailInfo.linkMan }}</el-descriptions-item>
          <el-descriptions-item label="责任人联系电话">{{ detailInfo.linkPhone }}</el-descriptions-item>
          <el-descriptions-item label="计划停工日期">{{ detailInfo.planStartDate }}</el-descriptions-item>
          <el-descriptions-item label="计划复工日期">{{ detailInfo.planEndDate }}</el-descriptions-item>
          <el-descriptions-item label="申请理由" :span="2">{{ detailInfo.reason }}</el-descriptions-item>
          <el-descriptions-item label="上传证明材料" :span="2"
            ><div v-for="item in detailInfo.attachments" :key="item.attachmentId" @click="download(item.attachmentId)">
              <!-- <el-link type="primary">primary</el-link> -->
              <el-button type="primary" link>{{ item.attachmentName }}</el-button>
            </div></el-descriptions-item
          >
        </el-descriptions>
        <el-form
          ref="addOrEditFormRef"
          v-loading="loading"
          :model="formData"
          :rules="rules"
          label-width="170"
          style="padding-right: 10px; overflow: auto"
        >
          <el-row justify="start" style="margin-top: 10px">
            <!--- 计划停工日期的选择范围最小为明天 -->
            <el-col v-if="dialogReAdd.type == 1" :span="itemSpan">
              <el-form-item label="计划停工日期" prop="planStartDate">
                <el-date-picker
                  v-model="formData.planStartDate"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disabledStartDate"
                  placeholder="选择日期"
                  @change="changePlanStartDate"
                />
              </el-form-item>
            </el-col>
            <el-col v-if="dialogReAdd.type == 1" :span="itemSpan">
              <el-form-item label="计划复工日期" prop="planEndDate">
                <el-date-picker
                  v-model="formData.planEndDate"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disabledEndDate"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="申请理由" prop="reason">
                <el-input
                  v-model="formData.reason"
                  type="textarea"
                  style="width: 100%"
                  :row="3"
                  placeholder="请输入申请理由"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2"> </el-col>
            <el-col :span="24">
              <el-form-item label="上传证明材料" prop="attachments">
                <el-upload
                  v-model:file-list="fileList"
                  :action="actionUrl"
                  multiple
                  :limit="5"
                  accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
                  :on-exceed="handleUploadExceed"
                  :on-success="handleUploadSuccess"
                  :on-preview="handleUploadPreview"
                >
                  <el-button plain size="small">上传附件</el-button>
                  <DownloadTemplate :type="templateType"></DownloadTemplate>
                  <template #tip>
                    <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogReAdd.footBtn }} </el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { useScreen } from "@/store/modules/screen";
import { GetAuditLogList, GetProjectLockOutForm, UpdateProjectLockOut } from "@/api/project/workapply/index";
import { ProjectLockOutEditForm, AttachmentsForm } from "@/api/project/workapply/types";
import { FormRules } from "element-plus/es/components/form/src/types";
import { downloadFile } from "@/utils";
import { downloadAttachment } from "@/api/common/other/index";
import moment from "moment";
import { UploadUserFile } from "element-plus";

//声明变量
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);

//声明变量
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(1200);
const props = defineProps({
  dialogReAdd: {
    type: Object,
    default: () => ({
      visible: false,
      title: "详情",
      footBtn: "详情",
      id: 0,
      type: 0, //0: 详情  1: 审核
    }),
  },
});
const { dialogReAdd } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);
const templateType = ref(105);
//上传文件列表
const fileList = ref<UploadUserFile[]>([]);

const formData = reactive<ProjectLockOutEditForm>({
  attachments: [],
  reason: "",
  status: 0,
});
const addOrEditFormRef = ref(ElForm);

const rules = reactive<FormRules<ProjectLockOutEditForm>>({
  reason: [{ required: true, message: "申请理由不能为空", trigger: "blur" }],
  planStartDate: [{ required: true, message: "计划停工日期不能为空", trigger: "blur" }],
  planEndDate: [{ required: true, message: "计划复工日期不能为空", trigger: "blur" }],
});

//工资信息
const detailInfo = ref({} as any);
//审核日志
const auditLog = ref([] as any[]);
const itemSpan = ref(12);

const download = (id: string) => {
  downloadAttachment(id).then((res) => {
    downloadFile(res);
  });
};

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 1000;

    itemSpan.value = 12;
  }
}

const initForm = function () {
  if (dialogReAdd.value.id) {
    loading.value = true;
    let loadCount = 0;
    //初始化审核日志
    GetAuditLogList(dialogReAdd.value.id)
      .then((res) => {
        if (res.type == 0) {
          if (res.success) {
            auditLog.value = res.data;
          } else {
            ElMessage({
              type: "error",
              message: res.msg,
            });
          }
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
        }
      })
      .finally(() => {
        loadCount++;
        loadCount === 2 && (loading.value = false);
      });
    //初始化详情
    GetProjectLockOutForm(dialogReAdd.value.id)
      .then((res) => {
        if (res.type == 0) {
          if (res.success) {
            detailInfo.value = res.data;
            Object.assign(formData, res.data);
          } else {
            ElMessage({
              type: "error",
              message: res.msg,
            });
          }
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
        }
      })
      .finally(() => {
        loadCount++;
        loadCount === 2 && (loading.value = false);
      });
  }
};

const disabledStartDate = (time: Date) => {
  return time.getTime() <= new Date(moment().add(-1, "days").format("YYYY-MM-DD")).getTime();
};
const disabledEndDate = (time: Date) => {
  if (formData.planStartDate) {
    return time.getTime() <= new Date(formData.planStartDate).getTime();
  }
  return time.getTime() > new Date(moment().format("YYYY-MM-DD")).getTime();
};
const changePlanStartDate = () => {
  formData.planEndDate = null;
};

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

onMounted(() => {
  initScreen();
  initForm();
  if (dialogReAdd.value.type == 1) {
    templateType.value = 105;
  }
  if (dialogReAdd.value.type == 2) {
    templateType.value = 102;
  }
});

//提交审核
const handleSubmit = () => {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (fileList.value.length > 0) {
        let attachments = [] as AttachmentsForm[];
        fileList.value.forEach((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              attachments.push({
                attachmentId: item.response.data,
              });
            }
          }
        });
        formData.attachments = attachments;
      }
      UpdateProjectLockOut(dialogReAdd.value.id, formData)
        .then((res) => {
          if (res.type == 0) {
            if (res.success) {
              ElMessage({
                type: "success",
                message: res.msg,
              });
              closeDialog(true);
            } else {
              ElMessage({
                type: "error",
                message: res.msg,
              });
            }
          }
        })
        .finally(() => (loading.value = false));
    }
  });
};

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
}
</script>

<style lang="scss" scoped>
:deep(.el-timeline) {
  max-height: 400px;
  overflow: hidden;
  scrollbar-width: none;
}
:deep(.el-timeline:hover) {
  overflow: auto;
}
::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

:deep(.el-textarea) {
  margin: 0;
}
:deep(.el-button > span) {
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline;
}
</style>
